<template>
  <view class="container">
    <!-- 自定义导航栏 -->
    <view class="custom-navbar">
      <view class="navbar-content">
        <view class="navbar-left" @click="goBack">
          <text class="back-icon">←</text>
        </view>
        <view class="navbar-title">添加好友</view>
        <view class="navbar-right"></view>
      </view>
    </view>

    <!-- 搜索区域 -->
    <view class="search-section">
      <view class="search-box">
        <input
          v-model="searchKeyword"
          placeholder="请输入用户名或手机号"
          class="search-input"
          @input="onSearchInput"
        />
        <button @click="handleSearch" class="search-btn">搜索</button>
      </view>
    </view>

    <!-- 搜索结果 -->
    <view class="search-results" v-if="searchResults.length > 0">
      <view class="result-title">搜索结果</view>
      <view
        v-for="user in searchResults"
        :key="user.userId"
        class="user-item"
      >
        <view class="user-avatar">
          <text class="avatar-text">{{ user.nickname ? user.nickname.charAt(0) : user.username.charAt(0) }}</text>
        </view>
        <view class="user-info">
          <view class="user-name">{{ user.nickname || user.username }}</view>
          <view class="user-username">用户名: {{ user.username }}</view>
        </view>
        <button
          @click="sendFriendRequest(user)"
          class="add-btn"
          :disabled="user.requestSent"
        >
          {{ user.requestSent ? '已发送' : '添加' }}
        </button>
      </view>
    </view>

    <!-- 空状态 -->
    <view class="empty-state" v-if="showEmpty">
      <text class="empty-text">{{ emptyText }}</text>
    </view>

    <!-- 加载状态 -->
    <view class="loading" v-if="loading">
      <text>搜索中...</text>
    </view>
  </view>
</template>

<script>
import { searchUsers, sendFriendRequest } from "@/utils/api.js";

export default {
  data() {
    return {
      searchKeyword: "",
      searchResults: [],
      loading: false,
      showEmpty: false,
      emptyText: "请输入关键词搜索用户",
    };
  },
  methods: {
    goBack() {
      uni.navigateBack();
    },

    onSearchInput() {
      if (!this.searchKeyword.trim()) {
        this.searchResults = [];
        this.showEmpty = false;
      }
    },

    async handleSearch() {
      if (!this.searchKeyword.trim()) {
        uni.showToast({
          title: "请输入搜索关键词",
          icon: "none",
        });
        return;
      }

      this.loading = true;
      this.showEmpty = false;

      try {
        const userInfo = uni.getStorageSync("userInfo");
        if (!userInfo) {
          uni.showToast({
            title: "请先登录",
            icon: "none",
          });
          return;
        }

        const result = await searchUsers(this.searchKeyword.trim());

        console.log("搜索结果:", result);

        if (result.code === 200) {
          this.searchResults = result.data.map(user => ({
            ...user,
            requestSent: false
          }));
          
          if (this.searchResults.length === 0) {
            this.showEmpty = true;
            this.emptyText = "未找到相关用户";
          }
        } else {
          uni.showToast({
            title: result.message || "搜索失败",
            icon: "none",
          });
          this.showEmpty = true;
          this.emptyText = "搜索失败，请重试";
        }
      } catch (error) {
        console.error("搜索用户失败:", error);
        uni.showToast({
          title: "网络错误，请重试",
          icon: "none",
        });
        this.showEmpty = true;
        this.emptyText = "网络错误，请重试";
      } finally {
        this.loading = false;
      }
    },

    async sendFriendRequest(user) {
      try {
        const userInfo = uni.getStorageSync("userInfo");
        if (!userInfo) {
          uni.showToast({
            title: "请先登录",
            icon: "none",
          });
          return;
        }

        // 后端从JWT token中获取当前用户ID，所以不需要传递fromUserId
        const result = await sendFriendRequest({
          toUserId: user.userId,
          message: "我想加你为好友",
        });

        console.log("发送好友申请结果:", result);

        if (result.code === 200) {
          // 更新按钮状态
          user.requestSent = true;
          this.$forceUpdate();

          uni.showToast({
            title: "好友申请已发送",
            icon: "success",
          });
        } else {
          uni.showToast({
            title: result.message || "发送失败",
            icon: "none",
          });
        }
      } catch (error) {
        console.error("发送好友申请失败:", error);
        uni.showToast({
          title: "网络错误，请重试",
          icon: "none",
        });
      }
    },
  },
};
</script>

<style scoped>
.container {
  min-height: 100vh;
  background-color: #ededed;
}

/* 自定义导航栏 */
.custom-navbar {
  background-color: #fff;
  padding-top: var(--status-bar-height, 44px);
  border-bottom: 1px solid #e5e5e5;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.navbar-content {
  height: 44px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 15px;
}

.navbar-left {
  width: 60px;
  display: flex;
  align-items: center;
}

.back-icon {
  font-size: 20px;
  color: #007aff;
  font-weight: 500;
}

.navbar-title {
  font-size: 17px;
  font-weight: 600;
  color: #333;
}

.navbar-right {
  width: 60px;
}

/* 搜索区域 */
.search-section {
  background-color: #fff;
  padding: 20px 15px;
  margin-bottom: 10px;
}

.search-box {
  display: flex;
  align-items: center;
  gap: 12px;
}

.search-input {
  flex: 1;
  height: 44px;
  padding: 0 20px;
  border: 1px solid #e5e5e5;
  border-radius: 22px;
  font-size: 16px;
  background-color: #f8f8f8;
  transition: border-color 0.2s ease;
}

.search-input:focus {
  border-color: #007aff;
  background-color: #fff;
}

.search-btn {
  height: 44px;
  padding: 0 24px;
  background-color: #07c160;
  color: white;
  border: none;
  border-radius: 22px;
  font-size: 16px;
  font-weight: 500;
  transition: background-color 0.2s ease;
}

.search-btn:active {
  background-color: #06ad56;
}

/* 搜索结果 */
.search-results {
  background-color: #fff;
  margin: 10px 15px;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.result-title {
  padding: 20px 15px 10px;
  font-size: 14px;
  font-weight: 500;
  color: #888;
  background-color: #f8f8f8;
}

.user-item {
  display: flex;
  align-items: center;
  padding: 20px 15px;
  border-bottom: 1px solid #f0f0f0;
  transition: background-color 0.2s ease;
}

.user-item:last-child {
  border-bottom: none;
}

.user-item:active {
  background-color: #f8f8f8;
}

.user-avatar {
  width: 50px;
  height: 50px;
  border-radius: 8px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.avatar-text {
  color: white;
  font-size: 20px;
  font-weight: 600;
  text-transform: uppercase;
}

.user-info {
  flex: 1;
}

.user-name {
  font-size: 17px;
  color: #333;
  margin-bottom: 4px;
  font-weight: 500;
}

.user-username {
  font-size: 14px;
  color: #888;
}

.add-btn {
  height: 36px;
  padding: 0 20px;
  background-color: #07c160;
  color: white;
  border: none;
  border-radius: 18px;
  font-size: 15px;
  font-weight: 500;
  transition: all 0.2s ease;
  box-shadow: 0 2px 8px rgba(7, 193, 96, 0.3);
}

.add-btn:active {
  background-color: #06ad56;
  transform: scale(0.98);
}

.add-btn:disabled {
  background-color: #e5e5e5;
  color: #999;
  box-shadow: none;
  transform: none;
}

/* 空状态 */
.empty-state {
  text-align: center;
  padding: 50px 20px;
}

.empty-text {
  color: #666;
  font-size: 14px;
}

/* 加载状态 */
.loading {
  text-align: center;
  padding: 20px;
  color: #666;
}
</style>
